﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
	/// <summary>
	/// 管理阴影Mesh类
	/// </summary>
	public sealed class ShadowMeshManager : Singleton<ShadowMeshManager>
	{
		private Dictionary<Material, SimpleShadowMesh> shadowDict = new Dictionary<Material, SimpleShadowMesh>();
		public struct SimpleShadowMeshStruct
        {
			public SimpleShadowMesh shadowmesh;
			public LinkedListNode<SimpleShadow> simpleShadowList;

			public bool IsHaveShadow()
            {
				return this.shadowmesh != null && this.simpleShadowList != null;
            }

			public void Clear()
            {
				this.shadowmesh = null;
				this.simpleShadowList = null;
            }

        }

		public SimpleShadowMeshStruct CreateShadowMesh(SimpleShadow shadow)
        {
			Material mat = shadow.ShadowMaterial;
			SimpleShadowMesh shadowMesh;
			if(!this.shadowDict.TryGetValue(mat,out shadowMesh))
            {
				GameObject go = new GameObject("ShadowMesh: " + mat.name);
				GameObject.DontDestroyOnLoad(go);
				shadowMesh = go.AddComponent<SimpleShadowMesh>();
				shadowMesh.SetMaterial(mat);
				this.shadowDict.Add(mat, shadowMesh);
            }
			var nodes = shadowMesh.Add(shadow);
			return new SimpleShadowMeshStruct
			{
				shadowmesh = shadowMesh,
				simpleShadowList = nodes
			};
        }

		public void Remove(SimpleShadowMeshStruct shadow)
        {
			shadow.shadowmesh.Remove(shadow.simpleShadowList);
        }
	}
}

